import java.util.ArrayList;
/*
题目描述：顺时针打印矩阵
注意只有一行或者一列的情况！
 */
public class E29 {
    public static void main(String[] args) {
//        int[][] matrix = {
//                {1,2,3,4},
//                {5,6,7,8},
//                {9, 10, 11,12},
//                {13,14,15,16}
//        };
//        int[][] matrix = {
//                {1,2},
//                {3,4}
//        };
        int[][] matrix = {
                {1},
                {2},
                {3},
                {4},
                {5}
        };
        ArrayList<Integer> res = printMatrix(matrix);
        for(int a : res){
            System.out.print(a  + " ");
        }
    }

    public static ArrayList<Integer> printMatrix(int [][] matrix) {

        ArrayList<Integer> res = new ArrayList<>();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return res;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int left = 0, top = 0, right = col - 1, bottom = row - 1;
        while(left <= right && top <= bottom){
            // left --> right
            for(int i = left; i <= right; i++){
                res.add(matrix[top][i]);
            }
            //top --> bottom
            for(int i = top +1; i <= bottom; i++){
                res.add(matrix[i][right]);
            }
            //right --> left
            //防止只有一行的情况
            if(top != bottom){
                for(int i = right - 1; i >= left; i--){
                    res.add(matrix[bottom][i]);
                }
            }

            //bottom --> top
            //防止只有一列的情况
            if(left != right){
                for(int i = bottom - 1; i > top; i--){
                    res.add(matrix[i][left]);
                }
            }

            left ++; top ++; right --; bottom --;
        }
        return res;
    }

}
/*
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
 */